#include "stdafx.h"
#include "directory.h"

namespace xm
{
	long directory_t::add_object( IKernelObject * obj )
	{
		if( !obj->Name() ) return E_UNEXPECTED;
		if( obj->MountedPlace() ) return E_FAIL;
		object_map_t::value_type val( ent_name(obj), obj ); 
		object_map_t::_Pairib ib = _objects.insert( val );
		if( !ib.second ) return E_FAIL;
		obj->MountOn( this );
		return S_OK;
	}
	long directory_t::del_object( LPCSTR name )
	{
		if( !name ) return E_INVALIDARG;
		find_key_t findk( name );
		object_map_t::iterator it = _objects.find( ent_name(&findk) );
		if( it == _objects.end() ) return E_UNEXPECTED;
		IKernelObject* op = it->second;
		_objects.erase( it );
		op->MountOn(0);
		return S_OK;
	}
	IKernelObject * directory_t::get_object( LPCSTR name )
	{
		if( !name ) return NULL;
		find_key_t findk( name );
		object_map_t::iterator it = _objects.find( ent_name(&findk) );
		if( it == _objects.end() ) return NULL;
		return it->second;
	}
	long directory_t::clear()
	{
		object_map_t::iterator it = _objects.begin();
		for( ; it != _objects.end(); ++ it )
			it->second->MountOn( 0 );
		_objects.clear();
		return S_OK;
	}
	size_t directory_t::entries()
	{
		return _objects.size();
	}
	IKernelObject * directory_t::get_next( LPCSTR name )
	{
		if( _objects.empty() ) 
			return NULL;

		if( !name ) return _objects.begin()->second;

		find_key_t keyo( name );
		object_map_t::iterator it = _objects.upper_bound( ent_name(&keyo) );
		if( it == _objects.end() )
			return 0;

		return it->second;
	}

	
	//long file_t::seek( int64_t dist, size_t from )
	//{
	//	if( from == SEEK_SET )
	//	{
	//		ptr = dist;
	//	}
	//	else if( from == SEEK_CUR )
	//	{
	//		ptr += dist;
	//	}
	//	else if( from == SEEK_END )
	//	{
	//		uint64_t fs = data->Length();
	//		if( fs == LENGTH_ERROR ) return E_FAIL;
	//		ptr = fs + dist;
	//	}
	//	else
	//	{
	//		return E_INVALIDARG;
	//	}
	//	return S_OK;
	//}

};
